<template>
    <div class="login-wrapper">
        <img class="app_login_title" src="@/assets/images/logoxjzn.png" alt="">
        <div class="app_login_title2">
            <div class="title1">无人车管理平台</div>
            <!-- <div  class="title2">让安全管理更科学、更透明、更高效</div> -->
        </div>
        <div class="login_box">
            <div class="login">
                <!--            <div class="offline-wrapper fr flex-center">-->
                <!--                <img style="width: 16px;height: 16px;" src="@/assets/images/offline.png" alt="">-->
                <!--                <div class="text">离线模式</div>-->
                <!--            </div>-->
                <div class="title">用户账号登录</div>
                <a-form ref="formRef" class="formState-wrapper" :model="formState" name="basic"
                    :wrapper-col="{ span: 24 }" autocomplete="off" :rules="rules">
                    <a-form-item label="" name="username" class="item">
                        <a-input size="large" v-model:value="formState.username" placeholder="请输入用户名"
                            autocomplete="off">
                            <template #suffix>
                                <img @click="clearUserName" style="cursor:pointer;width: 16px;height: 16px;"
                                    src="@/assets/images/close.png" alt="">
                            </template>
                        </a-input>
                    </a-form-item>
                    <a-form-item label="" name="password" class="item">
                        <a-input-password size="large" v-model:value="formState.password" placeholder="请输入密码">
                            <template #iconRender="isPassword">
                                <img style="width: 16px;height: 16px;" v-if="isPassword"
                                    src="@/assets/images/eye_open.png" alt="">
                                <img style="width: 16px;height: 16px;" v-else src="@/assets/images/eye_close.png"
                                    alt="">
                            </template>
                        </a-input-password>
                    </a-form-item>
                    <!-- <a-form-item v-if="verifyData.errNum >= 3"
                                 label=""
                                 name="code"
                                 class="item"
                    >
                        <a-input size="large" v-model:value="formState.code" placeholder="请输入验证码" autocomplete="off" >
                            <template #suffix>
                                <img @click="getVerifyData" style="width: 92px;height: 32px;cursor: pointer;" :src="verifyData.captchaImg">
                            </template>
                        </a-input>
                    </a-form-item> -->
                    <a-form-item label="" name="code" class="item">
                        <a-input size="large" v-model:value="formState.code" placeholder="请输入验证码" autocomplete="off">
                            <template #suffix>
                                <img @click="getVerifyData" style="width: 92px;height: 32px;cursor: pointer;"
                                    :src="verifyData.captchaImg">
                            </template>
                        </a-input>
                    </a-form-item>
                    <a-form-item class="item">
                        <a-button :loading="isLoading" @click="getLogin" type="primary" html-type="submit">登录</a-button>
                    </a-form-item>
                    <!-- <a-form-item name="remember" class="item">
                        <a-checkbox v-model:checked="formState.remember">保存账号密码</a-checkbox>
                    </a-form-item> -->
                </a-form>
            </div>
        </div>
    </div>

</template>

<script setup>
import { onMounted, reactive, ref } from 'vue';
import { getLoginUser, getVerify, login ,verifyCode} from '@/service/api'
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
// const Base64 = require("js-base64").Base64
const router = useRouter();
const formRef = ref()
const formState = reactive({
    username: '',
    password: '',
    code: '',
    // remember: false,
});
document.title = '无人车管理平台'
const validatorCode = async (_rule, code) => {
    if (code === '') {
        return Promise.reject('请输入验证码');
    }
    return Promise.resolve();
}
const rules = {
    username: [{ required: true, message: '请输入用户名' }],
    password: [{ required: true, message: '请输入密码' }],
    code: [{ required: true, validator: validatorCode }]
}
const isLoading = ref(false)
const verifyData = reactive({ // 接口获得的验证信息
    // errNum: localStorage.getItem('errNum') || 0,
    captchaCode: '', // 验证码
    captchaImg: '',  // 验证图片
    imgKey: '',
});

onMounted(() => {


    // if(localStorage.getItem('errNum')>=3){
    //     getVerifyData()
    // }
    // formState.remember = Boolean(localStorage.getItem('remember')==='1')
    // if (localStorage.getItem('username') && formState.remember) {
    //     formState.username = localStorage.getItem('username')
    //     formState.password = Base64.decode(localStorage.getItem('password'))// base64解密
    // }
    getVerifyData()
})

// 获取验证码
const getVerifyData = () => {
    verifyCode({
        "height": 32,
        "length": 4,
        "width": 92
    }).then(res => {
        if (res) {
            verifyData.captchaImg = res.result.base64Image
            verifyData.imgKey = res.result.imgKey
        }
    })
}

const getLoginUserData = (userInfo) => {
    localStorage.setItem('userInfo', JSON.stringify({}))
    let $userInfo = userInfo
    let resourceTree = userInfo.resourceTree.find(item => item.content =="pcMenu").childrenList ||[];
   
    console.log(resourceTree,'resourceTree');
    
    $userInfo.menuList = filterMenuType(resourceTree,$userInfo.resourceIdList||[],$userInfo.user.id)

    delete $userInfo.resourceTree
    localStorage.setItem('username', $userInfo.user.userName)
    localStorage.setItem('userInfo', JSON.stringify({...$userInfo,...$userInfo.user}));
    console.log($userInfo,'$userInfo');
    
    router.replace({ name: 'home' });
}
// 筛选'1'目录  '2'菜单 '3'按钮
const filterMenuType = (data,resourceIdList,id) => {
    let $list = []
    // .sort((a, b) => a.show_order - b.show_order)
    data.map(item => {
        //不为3则是菜单 目录 继续遍历
        if (item.type != 'button') {
            // 菜单需要子按钮里面有查询
            if (item.type == 'menu') {
                let $query = item.childrenList && item.childrenList.filter(cc => {
                    return cc.permission.includes(':query') && resourceIdList.includes(cc.id)
                })
                if($query || id == '1'){
                    if(item.isActive)$list.push(item);
                    // console.log('$list----1',$list);
                    // if(!firstUrl.value)firstUrl.value = item.content
                }
            } else {
                if(item.isActive)$list.push(item);
                // console.log('$list----2',$list);
            }

            if (item.childrenList){
                let childrenList = filterMenuType(item.childrenList,resourceIdList,id);
                item.childrenList = childrenList
            }
            // return item
        }
    });
    // console.log($list,'router--list');
    return $list;
}
// const KEY = CryptoJS.enc.Utf8.parse("0038zhxxptm8n9i0");//  内容可自定义  16位长度字符
// const IV = CryptoJS.enc.Utf8.parse("0000000000000000"); //  密钥偏移量    16位长度字符
// const aesFn = (str) => {
//     //默认自定义的约定密钥(与后端密钥保持一致)

//     let key = KEY
//     let iv = IV

//     //明文
//     let srcs = CryptoJS.enc.Utf8.parse(str);
//     // console.log("明文")
//     // console.log(srcs);
//     //加密
//     let encrypt = CryptoJS.AES.encrypt(srcs, key, {
//         iv: iv,
//         mode: CryptoJS.mode.CBC, //AES加密模式
//         padding: CryptoJS.pad.Pkcs7 //填充方式，这里后端是5 也可以用
//     });
//     // console.log("加密后");
//     // console.log(encrypt);
//     // console.log("base64加密");
//     // console.log(CryptoJS.enc.Base64.stringify(encrypt.ciphertext))
//     return CryptoJS.enc.Base64.stringify(encrypt.ciphertext); //返回base64格式密文
// }
// 点击登录
const getLogin = () => {
    formRef.value.validateFields().then(() => {
        isLoading.value = true
        // let params = {
        //     account: aesFn(formState.username),
        //     password: aesFn(formState.password),
        //     // captchaCode: formState.code,
        //     // captchaKey: verifyData.captchaKey,
        // }
        let params = {
            userName: formState.username,
            password: formState.password,
            verifyCode: formState.code,
            imgKey: verifyData.imgKey,
        }
        // console.log(3333, aesFn(formState.password));

        login(params).then(res => {
            if (res.status === "000_0000_0000") {  // 登录成功
                localStorage.setItem('token', res.result.token)
                getLoginUserData(res.result)

            } else {  // 登录失败
                isLoading.value = false
                // message.warning(res.data)
                getVerifyData()
            }
        }).catch(() => {
            isLoading.value = false;
            getVerifyData()
        })
        return true
    }).catch(() => {
        return false
    })
}


// 清除用户名
const clearUserName = () => {
    formState.username = null
}

</script>

<style lang="less" scoped>
.login-wrapper {
    background: url("@/assets/images/app_login_bg.png") no-repeat;
    background-size: cover;
    background-position: center;
    width: 100vw;
    height: 100vh;
    position: relative;
    .app_login_title {
        position: absolute;
        top: 5%;
        left: 7%;
        width: 300px;
        height: auto;

        // height: 50%;
        // text-align: center;
        // padding-left: 7%;
        // padding-top: 7%;
    }
    .app_login_title2 {
        position: absolute;
        top: 0;
        left: 0;
        width: 50%;
        height: auto;

        // height: 50%;
        // text-align: center;
        padding-left: 7%;
        padding-top: 7%;

        .title1 {
            font-family: PingFangSC-Semibold, PingFang SC, serif;
            text-shadow: 0 4px 20px rgba(0, 202, 255, 0.95);
            font-size: 60px;
            color: #cbfef9;
            font-weight: 700;
        }

        .title2 {
            font-family: PingFangSC-Semibold, PingFang SC, serif;
            text-shadow: 0 4px 20px rgba(0, 202, 255, 0.95);
            padding-top: 10px;
            font-size: 30px;
            color: #cbfef9;
            font-weight: 700;
        }
    }

    .login_box {
        padding: 8px;
        border-radius: 10px;
        overflow: hidden;
        position: absolute;
        top: 50%;
        right: 260px;
        width: 480px;
        height: 420px;
        transform: translateY(-50%);
        background: rgba(112, 200, 255, 0.24);
    }

    .login {
        width: 100%;
        height: 100%;
        background: #ffffff;
        border-radius: 10px;

        .offline-wrapper {
            width: 112px;
            height: 32px;
            background: #96c3ff;
            border-radius: 0 0 0 10px;
            cursor: pointer;

            .text {
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC, serif;
                font-weight: 400;
                color: #ffffff;
                margin-left: 8px;
            }
        }

        .title {
            font-size: 20px;
            font-family: PingFangSC-Semibold, PingFang SC, serif;
            font-weight: 600;
            color: #000000;
            padding: 72px 0 30px;
            text-align: center;
        }

        .formState-wrapper {
            padding: 0 22px;

            .item {
                margin: 10px;

                .wrc-input-affix-wrapper {
                    width: 100%;
                    height: 48px;
                    background: #ffffff;
                    border-radius: 6px;
                    border: 1px solid #9accff;
                }

                button {
                    width: 100%;
                    height: 48px;
                    background: #08f4f8;
                    border-color: #08f4f8;
                    border-radius: 10px;
                }

                .wrc-checkbox-wrapper {
                    font-size: 14px;
                    font-family: PingFangSC-Regular, PingFang SC, serif;
                    font-weight: 400;
                    color: #000000;
                }
            }
        }
    }
}
</style>
